package middleware

import (
	"fmt"
	"main/handlers"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

// AlarmConfigGroup 结构体统一处理探针请求
type AlarmConfig struct {
	AlarmConfigId          int    `json:"alarm_config_id"`                             // 探针ID（可选，更新或删除时需要）
	AlarmConfigGroupId     int    `json:"alarm_config_group_id" binding:"required"`    // 控制器名称（必填）
	AlarmConfigName        string `json:"alarm_config_name" binding:"required"`        // 探针名称（必填）
	AlarmConfigFormula     string `json:"alarm_config_formula"`                        // 配置公式（必填）
	AlarmConfigAction      string `json:"alarm_config_action" binding:"required"`      // 配置动作（必填）
	AlarmCorrectValue      string `json:"alarm_correct_value" binding:"required"`      // 告警阈值（必填）
	AlarmJudgmentFormula   string `json:"alarm_judgment_formula" binding:"required"`   // 判断方式（必填）
	AlarmStatus            int    `json:"alarm_status" binding:"omitempty,oneof=0 1"`  // 监控开关（必填）
	AlarmConfigLevelType   string `json:"alarm_config_level_type"  binding:"required"` // 告警级别（必填）
	AlarmConfigInstruction string `json:"alarm_config_instruction"`                    // 备注（可选）
	HostID                 int    `json:"host_id"`                                     // 主机（可选，主机指标绑定时需要）
}

// GetProbe 处理获取探针数据的请求
func GetProbe(c *gin.Context) {
	// 获取查询参数
	notBound := c.DefaultQuery("not_bound", "")   // 默认值为空
	projectID := c.DefaultQuery("project_id", "") // 可选字段，用于过滤
	hostId := c.DefaultQuery("host_id", "")       // 主机 ID

	// 构建 SQL 查询
	query := `
		SELECT 
			a.* 
		FROM 
			alarm_config a
		LEFT JOIN 
			alarm_config_group b 
		ON 
			a.alarm_config_group_id = b.alarm_config_group_id
		WHERE 
			a.alarm_config_del != 1
	`
	args := []interface{}{}

	// 添加条件过滤
	if notBound != "" {
		query += " AND a.host_id IS NULL"
	}

	if projectID != "" {
		query += " AND b.project_id = ?"
		args = append(args, projectID)
	}

	// 如果指定 hostId，需要通过 UNION 添加额外查询
	if hostId != "" && hostId != "undefined" {
		query = fmt.Sprintf(`(%s) UNION (
			SELECT 
				a.* 
			FROM 
				hosts c
			LEFT JOIN 
				alarm_config a 
			ON 
				c.host_id = a.host_id
			LEFT JOIN 
				alarm_config_group b 
			ON 
				a.alarm_config_group_id = b.alarm_config_group_id
			WHERE 
				c.host_id = ?
		)`, query)
		args = append(args, hostId)
	}

	// 执行查询
	results, err := handlers.ExecuteQuery(query, args...)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error":   "Error executing query",
			"details": err.Error(),
		})
		return
	}

	// 返回 JSON 响应
	c.JSON(http.StatusOK, results)
}

// PostController 处理新建探针的请求
func PostProbe(c *gin.Context) {
	var alarmConfig AlarmConfig

	// 解析请求体中的 JSON 数据
	if err := c.ShouldBindJSON(&alarmConfig); err != nil {
		// 请求体解析失败，返回 400 错误
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid data", "details": err.Error()})
		return
	}

	// 创建 SQL 插入语句
	insertsql := "INSERT INTO alarm_config (`alarm_config_group_id`, `alarm_config_name`, `alarm_config_formula`, `alarm_config_action`, `alarm_correct_value`, `alarm_judgment_formula`, `alarm_status`, `alarm_config_level_type`,`alarm_config_instruction`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);"

	// 执行 SQL 插入操作
	_, err := handlers.ExecuteNonQuery(insertsql,
		alarmConfig.AlarmConfigGroupId,
		alarmConfig.AlarmConfigName,
		alarmConfig.AlarmConfigFormula,
		alarmConfig.AlarmConfigAction,
		alarmConfig.AlarmCorrectValue,
		alarmConfig.AlarmJudgmentFormula,
		alarmConfig.AlarmStatus,
		alarmConfig.AlarmConfigLevelType,
		alarmConfig.AlarmConfigInstruction,
	)

	if err != nil {
		// 如果执行 SQL 查询失败，返回 500 错误
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Error executing query", "details": err.Error()})
		return
	}

	// 返回成功响应
	c.JSON(http.StatusOK, gin.H{"message": "新建探针成功"})
}

// PutController 处理更新探针的请求
func PutProbe(c *gin.Context) {
	var alarmConfig AlarmConfig

	// 解析请求体中的 JSON 数据
	if err := c.ShouldBindJSON(&alarmConfig); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid data", "details": err.Error()})
		return
	}

	// 校验 ID 是否存在
	if alarmConfig.AlarmConfigId == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "AlarmConfigGroup ID is required for updates"})
		return
	}

	// 创建 SQL 更新语句
	updateSQL := `
		UPDATE alarm_config
		SET alarm_config_group_id = ?, alarm_config_name = ?, alarm_config_formula = ?,
			alarm_config_action = ?, alarm_correct_value = ?, alarm_judgment_formula = ?, alarm_status = ?, alarm_config_level_type = ?, alarm_config_instruction = ?
		WHERE alarm_config_id = ?
	`

	// 执行 SQL 更新操作
	_, err := handlers.ExecuteNonQuery(updateSQL,
		alarmConfig.AlarmConfigGroupId,
		alarmConfig.AlarmConfigName,
		alarmConfig.AlarmConfigFormula,
		alarmConfig.AlarmConfigAction,
		alarmConfig.AlarmCorrectValue,
		alarmConfig.AlarmJudgmentFormula,
		alarmConfig.AlarmStatus,
		alarmConfig.AlarmConfigLevelType,
		alarmConfig.AlarmConfigInstruction,
		alarmConfig.AlarmConfigId,
	)

	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update alarm config group", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Alarm config group updated successfully"})
}

// DeleteControllers 处理删除探针的请求
func DeleteProbe(c *gin.Context) {
	var alarmConfig []AlarmConfig

	// 解析请求体中的 JSON 数据
	if err := c.ShouldBindJSON(&alarmConfig); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid data", "details": err.Error()})
		return
	}

	// 收集需要删除的探针 ID
	var alarmConfigIDs []int
	for _, alarmConfig := range alarmConfig {
		if alarmConfig.AlarmConfigId == 0 {
			c.JSON(http.StatusBadRequest, gin.H{"error": "AlarmConfigGroup ID is required for deletion"})
			return
		}
		alarmConfigIDs = append(alarmConfigIDs, alarmConfig.AlarmConfigId)
	}

	// 构造 SQL 语句中的占位符
	placeholders := make([]string, len(alarmConfigIDs))
	for i := range alarmConfigIDs {
		placeholders[i] = "?"
	}

	// 拼接完整的 SQL 语句
	deleteSQL := `
		UPDATE alarm_config
		SET alarm_config_del = 1
		WHERE alarm_config_id IN (` + strings.Join(placeholders, ",") + `)
	`

	// 将 ID 展开成可变参数
	args := make([]interface{}, len(alarmConfigIDs))
	for i, id := range alarmConfigIDs {
		args[i] = id
	}

	// 执行 SQL 删除操作
	_, err := handlers.ExecuteNonQuery(deleteSQL, args...)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete alarm config groups", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Alarm config groups deleted successfully"})
}
